import os
from celery import Celery
from kombu import Exchange, Queue

# 设置默认的Django设置模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'deep_test.settings')

# 创建Celery实例
app = Celery('deep_test')

# 基本配置
app.conf.update(
    # 消息代理配置
    broker_url='redis://localhost:6379/0',
    result_backend='redis://localhost:6379/0',

    # 时区设置
    timezone='Asia/Shanghai',
    enable_utc=False,

    # 序列化配置
    task_serializer='json',
    result_serializer='json',
    accept_content=['json'],

    # Worker 配置
    worker_prefetch_multiplier=1,
    worker_max_tasks_per_child=50,
    worker_max_memory_per_child=200000,  # 200MB

    # 任务配置
    task_always_eager=False,
    task_acks_late=True,
    task_reject_on_worker_lost=True,
    task_track_started=True,
    task_time_limit=600,  # 10分钟
    task_soft_time_limit=540,  # 9分钟

    # 队列配置
    task_default_queue='default',
    task_queues=(
        Queue('default', Exchange('default'), routing_key='default'),
    ),
    task_default_exchange='default',
    task_default_exchange_type='direct',
    task_default_routing_key='default',
)

# 从Django设置文件中加载Celery配置
app.config_from_object('django.conf:settings', namespace='CELERY')

# 自动从所有已注册的Django应用中加载任务
app.autodiscover_tasks(['exam_system'])

@app.task(bind=True)
def debug_task(self):
    """Debug task to verify Celery configuration"""
    print(f'Request: {self.request!r}')
    return {'status': 'success', 'request': str(self.request)}

if __name__ == '__main__':
    app.start()